import React, { useState, useRef, useEffect } from 'react';
import {Modal, Radio, Row, Col, message, Button, Space} from 'antd';
import ProForm, { ProFormText, ProFormSelect } from '@ant-design/pro-form';
import { useForm } from 'antd/es/form/Form';
import { CONFIG_LINK_CATEGORY, DELETE_LINK_CATEGORY } from './consts';
import {
  insertLinkType,
  getLinkTypeList,
  updateLinkType,
  deleteLinkTypeById,
} from '@/services/linkManager';
import type { ProFormInstance } from '@ant-design/pro-components';
import {CheckOutlined, SyncOutlined, UndoOutlined} from '@ant-design/icons';

export type FormValueType = {
  target?: string;
  template?: string;
  type?: string;
  time?: string;
  frequency?: string;
} & Partial<API.RuleListItem>;
export type UpdateFormProps = {
  onCancel: (flag?: boolean, formVals?: FormValueType) => void;
  onSubmit: (values: FormValueType) => Promise<void>;
  updateModalVisible: boolean;
  values: Partial<API.RuleListItem>;
};

const ConfigLinksCategoryForm: React.FC<UpdateFormProps> = (props) => {
  const [formAddLinkType] = useForm();
  const [formModifyLinkType] = useForm();
  const [linkTypeOptions, setLinkTypeOptions] = useState([]);
  const [disableLinksCategory, setDisableLinksCategory] = useState(false);
  const [radioSelectTarget, setRadioSelectTarget] = useState(CONFIG_LINK_CATEGORY);
  const [selectedCategoryID, setSelecetedCategoryID] = useState('');
  const actionRef = useRef<ActionType>();
  const [modalVisible, setModalVisible] = useState(true);
  const formRef = useRef<ProFormInstance>();
  const formLayout1 = {
    labelCol: {
      span: 6,
    },
    wrapperCol: {
      span: 14,
    },
  };
  const formLayout2 = {
    labelCol: {
      span: 10,
    },
    wrapperCol: {
      span: 16,
    },
  };

  const addLinkType = async () => {
    const hide = message.loading('正在添加');

    const names = formAddLinkType.getFieldsValue();
    if (names.usefulLinksCategory === undefined || names.usefulLinksCategory === '') {
      hide();
      return;
    }
    try {
      await insertLinkType({
        name: names['usefulLinksCategory'],
      });
      syncTypeList();
      hide();
      message.success('添加成功！');
    } catch (error) {
      hide();
      message.error('添加失败，请重试！' + error.response.data.message);
    }
  };

  const modifyLinkType = async () => {
    if (radioSelectTarget === CONFIG_LINK_CATEGORY) {
      const targetCategoryName = formModifyLinkType.getFieldsValue();
      if (selectedCategoryID === '') {
        return;
      }
      if (targetCategoryName.modification_link_type === undefined) {
        return;
      }
      const hide = message.loading('正在配置');
      try {
        await updateLinkType({
          id: selectedCategoryID,
          name: targetCategoryName && targetCategoryName.modification_link_type,
        });
        hide();
        syncTypeList();
        message.success('已编辑！');
        return true;
      } catch (error) {
        hide();
        message.error('编辑失败！' + error.response.data.message);
        return false;
      }
    } else if (radioSelectTarget === DELETE_LINK_CATEGORY) {
      const hide = message.loading('正在配置');
      try {
        await deleteLinkTypeById({
          id: selectedCategoryID,
        });
        hide();
        syncTypeList();
        message.success('已删除！');
        return true;
      } catch (error) {
        hide();
        message.error('删除失败！');
        message.error(error.response.data.message);
        return false;
      }
    }
  };

  const onReset = () => {
    setModalVisible(false);
    props.onCancel();
  };

  const syncTypeList = async () => {
    const msg = await getLinkTypeList();
    let res = [];
    msg.data.map((item) => {
      let temp = {};
      temp['label'] = item.name;
      temp['value'] = item.id;
      res.push(temp);
    });
    // setLinkTypeOptions(prev => {
    //   return Array.from(new Set([...prev, ...res]))
    // });
    formModifyLinkType.resetFields();
    formAddLinkType.resetFields();
    setLinkTypeOptions(res);
    // if(actionRef.current)
    //   actionRef.current.reload()
    // formRef.current.setFieldValue(
    //   "links_category", res
    // )
  };

  useEffect(() => {
    syncTypeList();
  }, []);
  const changeLinkCateRadio = (item1) => {
    if (item1.target.value === CONFIG_LINK_CATEGORY) {
      setRadioSelectTarget(CONFIG_LINK_CATEGORY);
      setDisableLinksCategory(false);
    } else if (item1.target.value === DELETE_LINK_CATEGORY) {
      setRadioSelectTarget(DELETE_LINK_CATEGORY);
      setDisableLinksCategory(true);
    }
  };

  const selectLinksCategory = (value: string | number | LabeledValue, option: Option) => {
    setSelecetedCategoryID(option && option.value);
  };

  return (
    <Modal
      // title="编辑用户"
      title={'设置友情链接分类'}
      width="900px"
      destroyOnClose
      open={props.updateModalVisible}
      onCancel={props.onCancel}
      footer={null}
    >
      <ProForm
        form={formAddLinkType}
        layout="horizontal"
        {...formLayout1}
        // initialValues={props.values}
        onReset={onReset}
        submitter={{
          render: (_, dom) => (
            <div style={{ display: 'flex', justifyContent: 'center' }}>
              <Space>
                {/*{dom}*/}
                {<Button onClick={() => {
                  _.reset()
                }}><UndoOutlined />取消</Button>}
                {<Button type={"primary"} onClick={() => {
                  _.submit()
                }}><CheckOutlined />确定</Button>}

              </Space>
            </div>
          ),
        }}
      >
        <ProFormText
          rules={[
            {
              required: true,
              message: '友情链接分类必填',
            },
          ]}
          width="md"
          name="usefulLinksCategory"
          placeholder="请填写友情链接分类"
          label="添加友情链接分类"
        />
      </ProForm>
      <ProForm
        style={{
          marginTop: 20,
        }}
        form={formModifyLinkType}
        layout="horizontal"
        {...formLayout2}
        initialValues={props.values}
        // onFinish={}
        onReset={onReset}
        formRef={formRef}
        // actionRef = {actionRef}
        submitter={{
          render: (_, dom) => (
            <div style={{ display: 'flex', justifyContent: 'center' }}>
              <Space>
                {/*{dom}*/}
                {<Button onClick={() => {
                  _.reset()
                }}><UndoOutlined />取消</Button>}
                {<Button type={"primary"} onClick={() => {
                  _.submit()
                }}><CheckOutlined />确定</Button>}

              </Space>
            </div>
          ),
        }}
      >
        <Row style={{ width: '100%' }} gutter={16}>
          <Col span={10} className="gutter-row">
            <ProFormSelect
              // width="60%"
              label="修改友情链接分类"
              name="links_category"
              options={linkTypeOptions}
              onChange={selectLinksCategory}
              placeholder="请选择"
              rules={[
                {
                  required: true,
                  message: '请选择要修改的分类',
                },
              ]}
              // request={
              //   async () => {
              //     // 这里需要返回一个 Promise,在返回之前你可以进行数据转化
              //     // 如果需要转化参数可以在这里进行修改
              //     const msg = await getLinkTypeList();
              //     let res = []
              //     msg.data.map(item => {
              //       let temp = {};
              //       temp['label'] = item.name;
              //       temp['value'] = item.id;
              //       res.push(temp)

              //     })
              //     return res;
              //   }
              // }
            />
          </Col>
          <Col span={3} className="gutter-row">
            <Button type="primary" onClick={syncTypeList}>
              <SyncOutlined />
            </Button>
          </Col>
          <Col
            span={10}
            className="gutter-row"
            style={{
              display: disableLinksCategory ? 'none' : 'block',
            }}
          >
            <ProFormText
              rules={[
                {
                  required: true,
                  message: '请填写修改为的分类',
                },
              ]}
              // width="100%"
              name="modification_link_type"
              // disabled={disableLinksCategory}
              // placeholder="请填写友情链接分类"
              label="修改为"
            />
          </Col>
        </Row>

        <Radio.Group
          style={{
            marginLeft: 50,
          }}
          onChange={changeLinkCateRadio}
          defaultValue={CONFIG_LINK_CATEGORY}
        >
          <Radio value={CONFIG_LINK_CATEGORY}>修改所选的友情链接分类</Radio>
          <Radio value={DELETE_LINK_CATEGORY}>删除所选的友情链接分类</Radio>
        </Radio.Group>
      </ProForm>
    </Modal>
  );
};

export default ConfigLinksCategoryForm;
